package com.younio.local.entity;

import com.younio.local.util.Objects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigInteger;
import java.util.Arrays;

/**
 * @author lan  [1728209643@qq.com]
 * @create 2019-01-10 19:15
 * @desc 表号
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TbNo {

    private String indentId;

    private String matUuid;

    private BigInteger val;
    private String tbValue;

    private String fr = "校表";

    private String prefix;

    private String tbNoStart;
    private String tbNoEnd;

    private BigInteger start;
    private BigInteger end;

    private boolean inited;


    public void setTbNoStart(String tbNoStart) {
        this.tbNoStart = tbNoStart;
        init();
    }

    public void setTbNoEnd(String tbNoEnd) {
        this.tbNoEnd = tbNoEnd;
        init();
    }

    private void init() {
        if (inited) {
            return;
        }
        if (Objects.strIsEmpty(this.tbNoStart) || Objects.strIsEmpty(this.tbNoEnd)) {
            return;
        }
        try {
            this.prefix = getPrefix(tbNoStart);
            this.start = new BigInteger(tbNoStart.replace(prefix, ""));
            this.end = new BigInteger(tbNoEnd.replace(prefix, ""));
            this.inited = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getPrefix(String tbNo) {
        if (tbNo != null) {
            char[] chars = tbNo.toCharArray();
            int k = -1;
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] < '0' || chars[i] > '9') {
                    k = i;
                }
            }
            return k == -1 ? "" : new String(Arrays.copyOfRange(chars, 0, k + 1));
        }
        return null;
    }

    public static boolean match(TbNo tbNo, BigInteger tb) {
        try {
            tbNo.init();
            BigInteger start = tbNo.getStart();
            BigInteger end = tbNo.getEnd();
            if (start.compareTo(tb) <= 0 && end.compareTo(tb) >= 0) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
